<template>

    <div class="qzq">
        <div class="qzqContent">
            <div class="qzqbar">
                <div class="demoname">签名:<b>{{msubInfo.name}}</b></div>
                <div @click="reset()" class="clearname" style="text-align: center; color:#08F;" :style="{color:$store.state.themcolor}">清除</div>
                <div @click="close()" class="clearname"
                     style="position:relative; color:red; top:-3px; font-size:18px; text-align: right"><i
                    class="el-icon-close"></i>
                </div>

            </div>
            <div class="canvasqz">
                <iframe id="qzq" class="qzban" v-if="showqianzi" ref="qzq" frameborder="0"
                        src="./static/signature.html"></iframe>
            </div>
            <div style="margin:10px;">
                <!--<el-button   @click="saveqzq" :disabled="showDisabled">{{showDisabled?'签约中...':'立即签约'}}</el-button>-->

                <div class="sbtns"   @click="saveqzq()"  :style="{background:$store.state.themcolor}">立即签约</div>
            </div>
        </div>
    </div>

</template>

<script>
    //base64转blob
    function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new Blob([u8arr], {type: mime})
    }

    //将blob转换为file
    function blobToFile(theBlob, fileName) {
        theBlob.lastModifiedDate = new Date()
        theBlob.name = fileName
        return theBlob
    }
    import axios from 'axios'
    import { HOST, OSS_API_HOST } from '@/constants'


    export default {
        props: ['showQz', 'numbs', 'cmid', 'qname', 'return_url','msubInfo'],
        name: 'qianzi',

        data() {
            return {
                showDisabled: false,
                showqianzi: false,
                islaodings: null,
                ossupUrl: 'https://renshe.oss-cn-beijing.aliyuncs.com/',
            }
        },
        mounted() {

            this.showqianzi = true;
        },
        methods: {

            saveqzq() {
                var img = document.getElementById('qzq').contentWindow
                let returnImg = img.canvas.toDataURL('image/png')
                console.log(returnImg)
                if(!img.isSign){
                  alert('请手写签名')
                  return  false;
                }

                var _blob = dataURLtoBlob(returnImg)
                window.qzImg = _blob;
                var suffix = returnImg.split(';')[0].split(':')[1].split('/')[1]//文件扩展名
                var filename = String(new Date().getTime()) + '.' + suffix
                var _file = blobToFile(_blob, filename)
                if (_file.size > 512 * 1024) {
                    this.$toast('签名图片过大，请重新签名')
                    return false
                }
                this.showDisabled = true

              this.saveqm().then(res=>{
                return this.ossUpload(res)

              }).then(res=>{
                return this.saveqz(res)
              }).then(res=>{

                var tempSaveinfo={

                  psnAttachList:[
                    {
                      attachmentId:this.$store.state.personInfo.zmattid,
                      fileName:'正面',
                      fileType:'FRONT'
                    },{
                      attachmentId:this.$store.state.personInfo.fmattid,
                      fileName:'反面',
                      fileType:'BACK'
                    },
                    {
                      "attachmentId":this.$store.state.personInfo.videoattid,
                      "fileName":"视频",
                      "fileType":"IDENTITY"
                    },
                    {
                      "attachmentId":res.data,
                      "fileName":"签字",
                      "fileType":'ESIGN'
                    }

                  ]
                }
                return this.saveallinfo(tempSaveinfo)

              }).then(res=>{
                this.callback('')

              },error=>{

                this.callback(error)


              })



            },
          saveallinfo(obj){
            return new Promise((resolve, reject) => {
              this.$http.post('yxc/wxuser/reg/finalSubmitReg',obj).then((res) => {
                // that.ossUpload(res.data);
                if(res.code == 200){
                  resolve(res)
                }else(
                  reject(res.message)
                )

              }, error => {
                reject('保存接口调用失败')
              })

            })
          },
          saveqm() {//保存base64

                return new Promise((resolve, reject) => {
                  this.$http.get(OSS_API_HOST + 'oss/signature/youxiangche').then((res) => {
                    // that.ossUpload(res.data);
                    resolve(res)
                  }, error => {
                    reject('获取签名失败')
                  })

                })
          },
          ossUpload(sign) {//上传到阿里云

            let that = this;
            // alert(window.qzImg)
            //
            // var _blob = dataURLtoBlob(window.qzImg)
            // var suffix = window.qzImg.split(';')[0].split(':')[1].split('/')[1]//文件扩展名
            var filename = String(new Date().getTime()) + 'qzs.png'
            var _file = blobToFile(window.qzImg, filename)

            var newfiles = _file //base64ToBlob(window.qzImg)

            let fileOfBlob = newfiles;
            console.log(fileOfBlob.size+'MMMMMMMMMMMMMMMMM')


            console.log('*****************')
            console.log(newfiles)
            console.log(newfiles.size)
            console.log('*****************')
            let data = {
              "key": "string",
              "name": "string",
              "type": "string",
              "vpath": "string"
            }
            /* eslint-disable no-undef */
            const instance = axios.create({
              timeout: 100000,
              headers: {'Content-Type': 'multipart/form-data'}
            })


            var randm = Math.ceil(Math.random()*1000000)+'';
            var chuo = new Date().getTime() +randm;
            // alert(chuo)
            let param = new FormData()  // 创建form对象
            param.append('chunk', '0') // 添加form表单中其他数据
            param.append('OSSAccessKeyId', sign.data.accessid) // 添加form表单中其他数据
            param.append('policy', sign.data.policy) // 添加form表单中其他数据
            param.append('Signature', sign.data.signature) // 添加form表单中其他数据
            param.append('Expires', sign.data.expire) // 添加form表单中其他数据
            param.append('key', sign.data.dir + chuo) // 添加form表单中其他数据
            param.append('success_action_status', '200') // 添加form表单中其他数据
            param.append('success_action_statusText', 'ok') // 添加form表单中其他数据
            param.append('Access-Control-Allow-Origin', '*') // 添加form表单中其他数据
            param.append('file', fileOfBlob, chuo)  // 通过append向form对象添加数据


            return new Promise((resolve, reject)=>{


            instance.post(sign.data.host, param).then(response => {
              console.log(response)
              console.log('-----------------------------------')
              that.ossloading = false;
              if (response.status == 200) {


                let rimg = {
                  key: sign.data.dir + chuo,
                  name: chuo+'.png'
                }
                resolve(rimg)

              } else {
                // alert('sssssssssssssssss')
              }
            }, error => {
              reject()

            })
            })

          },
          saveqz(obj){
            return new Promise((resolve, reject) => {
              this.$http.post(OSS_API_HOST + 'oss/file',obj).then(res=>{
                if(res.code == 200){
                  resolve(res)
                }else{
                  reject()
                }
              })
            })

          },
            reset() {
                document.getElementById('qzq').contentWindow.clearcanvas()
            },
            closepp() {
                this.$parent.$parent.closepp()
            }

        }
    }
</script>

<style lang="scss" scoped>

.sbtns{
  border-radius:5px;
  text-align:center;
  padding:10px 0;
  color:#FFF;
}
    .qzban {
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        height: 100%;
        width: 100%;

    }

    .canvasqz {
        height: 300px;
        position: relative;
        border: 1px solid #DDD;
        overflow: hidden;
        margin-bottom: 10px;
    }

    .qzq {
        position: absolute;
        left: 0;
        right: 0;
        z-index: 9999;
        bottom: 0;
        background: #FFF;

    .qzqContent {

    .qzqbar {
        font-size: 13px;
        display: flex;
        padding: 10px;

    .demoname {
        text-align: left;
        width: 100%;
    }

    .clearname {
        text-align: right;
        width: 100%;
        position: relative;

    i {
        display: inline-block;
        width: 50px;

    img {
        width: 100%;
    }

    position: relative

    ;
    top:

    10
    px

    ;
    margin-right:

    10
    px

    ;
    }

    }

    }
    }
    }

</style>
